package com.bayss.core.service.sku;

import com.bayss.core.constant.ResultMsg;
import com.bayss.core.entity.classify.Classify;
import com.bayss.core.entity.classify.ClassifyExample;
import com.bayss.core.entity.classify.ClassifyItemExample;
import com.bayss.core.entity.classify.mapper.ClassifyItemMapper;
import com.bayss.core.entity.classify.mapper.ClassifyMapper;
import com.bayss.core.entity.goods.Sku;
import com.bayss.core.entity.goods.SkuExample;
import com.bayss.core.entity.goods.Spu;
import com.bayss.core.entity.goods.SpuExample;
import com.bayss.core.entity.goods.mapper.SkuMapper;
import com.bayss.core.entity.goods.mapper.SpuMapper;
import com.bayss.core.model.SpuQuery;
import com.bayss.core.util.FileUtil;
import com.bayss.core.util.SkuUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by LDL on 2019/12/9.
 */
@Service
public class SpuService {
    private static Logger logger = LogManager.getLogger();
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private ClassifyMapper classifyMapper;
    @Autowired
    private ClassifyItemMapper classifyItemMapper;
    @Autowired
    private SkuMapper skuMapper;

    /**
     * 分页查询
     */
    public PageInfo<Spu> getByPage(Integer page, Integer pageSize, SpuQuery spuQuery) {
        SpuExample example = new SpuExample();
        SpuExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(1);
        if (spuQuery != null && spuQuery.getSpuName() != null) {
            criteria.andSpuNameCnLike("%" + spuQuery.getSpuName() + "%");
        }
        if (spuQuery != null && spuQuery.getId() != null) {
            criteria.andIdEqualTo(spuQuery.getId());
        }
        example.setOrderByClause("create_time desc");
        PageHelper.startPage(page, pageSize);
        PageInfo<Spu> result = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> spuMapper.selectByExample(example));
        return result;
    }

    /**
     * 根据spuCode查询spu列表
     *
     * @return
     */
    public List<Spu> list(Spu spuQuery) {
        SpuExample example = new SpuExample();
        SpuExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(1);
        if (spuQuery != null && StringUtils.isNotEmpty(spuQuery.getSpuCode())) {
            example.createCriteria().andSpuCodeEqualTo(spuQuery.getSpuCode());
        }
        if (spuQuery != null && spuQuery.getId() != null) {
            criteria.andIdEqualTo(spuQuery.getId());
        }
        List<Spu> spuList = spuMapper.selectByExample(example);

        for (Spu spu : spuList) {
            List<String> classifyCodeList = SkuUtil.parseSpuCode(spu.getSpuCode());
            if (classifyCodeList.size() == 0) {
                continue;
            }
            //sku_time_code_code_code
            ClassifyExample classifyExample = new ClassifyExample();
            classifyExample.createCriteria().andCodeIn(classifyCodeList);
            List<Classify> classifyList = classifyMapper.selectByExample(classifyExample);

            for (Classify classify : classifyList) {
                ClassifyItemExample classifyItemExample = new ClassifyItemExample();
                classifyItemExample.createCriteria().andClassifyIdEqualTo(classify.getId());
                classify.setClassifyItems(classifyItemMapper.selectByExample(classifyItemExample));
            }
            spu.setClassifyList(classifyList);
        }
        return spuList;
    }

    /**
     * 根据id删除
     */
    public void deleteById(Integer id) {
        Spu spuDB = spuMapper.selectByPrimaryKey(id);
        if (spuDB != null && spuDB.getSpuCode().contains("self_spu_")) {
            logger.error("自选餐，配置性数据不能删除");
            return;
        }

        Spu spuUpdate = new Spu();
        spuUpdate.setId(spuDB.getId());
        spuUpdate.setStatus(0);
        spuMapper.updateByPrimaryKeySelective(spuUpdate);
        // 删除关联的sku
        deleteSkuBySpuCode(spuDB.getSpuCode());
    }

    /**
     * 更新spu
     */
    public void update(Spu spu) {
        Spu spuDB = spuMapper.selectByPrimaryKey(spu.getId());
        if (spuDB != null && spuDB.getSpuCode().contains("self_spu_")) {
            logger.error("自选餐，配置性数据不能删除");
            return;
        }
        if (spuDB == null) {
            return;
        }

        spu.setSpuCode(SkuUtil.getSpuCodeFirst(spuDB.getSpuCode()) + spu.getSpuCode());

        spu.setSpuImageCn(FileUtil.formatImgUrl(spu.getSpuImageCn()));
        spu.setSpuImageEn(FileUtil.formatImgUrl(spu.getSpuImageEn()));
        spu.setSpuImageKo(FileUtil.formatImgUrl(spu.getSpuImageKo()));

        Sku sku = new Sku();
        sku.setClassifyId(spu.getClassifyId());
        SkuExample skuExample = new SkuExample();
        skuExample.createCriteria().andSpuCodeEqualTo(spu.getSpuCode());
        skuMapper.updateByExampleSelective(sku, skuExample);

        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 新建spu
     */
    public ResultMsg add(Spu spu) {
        spu.setSpuCode(SkuUtil.formatSpuCode(spu.getSpuCode()));
        spu.setCreateTime(new Date());
        spu.setSalesMonth(0);
        spu.setSalesMonthInjection(spu.getSalesMonthInjection() == null ? 0 : spu.getSalesMonthInjection());
        spu.setSpuImageCn(FileUtil.formatImgUrl(spu.getSpuImageCn()));
        spu.setSpuImageEn(FileUtil.formatImgUrl(spu.getSpuImageEn()));
        spu.setSpuImageKo(FileUtil.formatImgUrl(spu.getSpuImageKo()));

        spuMapper.insertSelective(spu);
        return ResultMsg.success();
    }

    public Spu findBySpuCode(String spuCode) {
        SpuExample example = new SpuExample();
        example.createCriteria().andSpuCodeEqualTo(spuCode).andStatusEqualTo(1);
        List<Spu> list = spuMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    public void deleteSkuBySpuCode(String spuCode) {
        Sku sku = new Sku();
        sku.setStatus(0);
        SkuExample skuExample = new SkuExample();
        skuExample.createCriteria().andSpuCodeEqualTo(spuCode);
        skuMapper.updateByExampleSelective(sku, skuExample);
    }
}
